import { DataService } from '@services/data.service';
import { Component, OnInit, ElementRef, Renderer2 } from '@angular/core';
import {
  NavController,
} from '@ionic/angular';

import { RoomPage } from '../room/room';
import { ActivatedRoute, Router } from '@angular/router';
import { EmitService } from '@services/emit.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'system',
  templateUrl: 'page.html',
  styleUrls: ['style.scss']
})
export class SystemPage implements OnInit {
  projectId;
  projectName;
  system;
  roomGroup = [];
  Page;
  alarmList = [];
  iconShow = true;
  roomList = [
    { RoomName: '配电房1' },
    { RoomName: '配电房2' },
    { RoomName: '配电房3' },
    { RoomName: '配电房4' },
    { RoomName: '配电房5' },
  ];
  autoScrollInterval = null;  // 告警消息定时器
  temperature = null;
  humidity = null;
  faultList = []
  constructor(
    public navCtrl: NavController,
    public dataservice: DataService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private emitService: EmitService,
    public el: ElementRef,
    public renderer: Renderer2,
  ) {
    // this.projectId = this.navParams.get('projectId')
    //   ? this.navParams.get('projectId')
    //   : '12';
    // this.projectName = this.navParams.get('projectName')
    //   ? this.navParams.get('projectName')
    //   : '默认项目';
    // this.system = this.navParams.get('system')
    //   ? this.navParams.get('system')
    //   : '';
    this.activatedRoute.queryParams.subscribe(params => {
      this.projectId = params.projectId
        ? params.projectId
        : '12';
      this.projectName = params.projectName
        ? params.projectName
        : '默认项目';
      this.system = params
        ? params
        : '';
      this.iconShow = params.iconShow === 'false' ? false : true
    });
  }

  ngOnInit() {
    // if (this.projectId) {
    //   this.getSystemList(this.projectId, this.system.deviceSysId);
    // }
  }

  ionViewWillEnter() {
    if (this.projectId) {
      this.getAlarmList(this.projectId, this.system.deviceSysId);
      this.getWeatherList();
      // this.getDevicesList(this.projectId, this.system.deviceSysId);
      this.getSystemList(this.projectId, this.system.deviceSysId);
      const elements = document.querySelectorAll('ion-tab-bar');
      if (elements != null) {
        Object.keys(elements).map((key) => {
          elements[key].style.display = 'none';
        });
      }
    }
  }

  getWeatherList() {
    this.dataservice.getWeatherList(this.projectId).subscribe(res => {
      if (res.success && res.data) {
        this.temperature = res.data.temperature;
        this.humidity = res.data.humidity;
      }
    })
  }

  autoScroll(len) {
    const step = -90;
    let top = 1;
    const ele = this.el.nativeElement.querySelector('.Text-init');
    if (this.autoScrollInterval) {
      clearInterval(this.autoScrollInterval);
      this.renderer.setStyle(ele, 'transition', 'unset');
      this.renderer.setStyle(ele, 'top', 0 + 'px');
    }
    this.autoScrollInterval = setInterval(() => {
      if (top < len) {
        this.renderer.setStyle(ele, 'top', top * step + 'px');
        if (top === 1) {
          this.renderer.setStyle(ele, 'transition', 'top 1s');
        }
        top++;
      } else {
        top = 0;
        this.renderer.setStyle(ele, 'transition', 'unset');
      }
    }, 2000);
  }

  getAlarmList(projectId, deviceSysId) {
    this.dataservice.getSystemsAlarmList(projectId, deviceSysId).subscribe(res => {
      if (res.success && res.data) {
        this.alarmList = res.data.filter(item => { return item.deviceSystemId === +this.system.deviceSysId })
        this.autoScroll(this.alarmList.length);
      }
    })
  }

  getSystemList(projectId, deviceSysId) {
    this.dataservice.getDeviceParams(projectId, deviceSysId).subscribe(res => {
      this.dealData(res.data).subscribe(res => {
        this.roomGroup = res.rooms;
      })
    });
  }

  getDevicesList(projectId, deviceSysId) {
    this.dataservice.getDevicelist(projectId, deviceSysId).subscribe(res => {
      if (res.success && res.data) {
        const requestData = res.data.datas.map(item => {
          return {
            deviceId: item.deviceId,
            deviceParameterCode: 2
          }
        })
        this.dataservice.getDeviceRealParams(requestData).subscribe(res => {
          if (res.success && res.data) {
            this.faultList = res.data.datas.filter(item => { return item.value === 1 })
          }
        })
      }
    })
  }

  toPage(room, index) {
    const data = {
      projectId: this.projectId,
      deviceSysId: this.system.deviceSysId,
      sysName: this.system.deviceSysName,
      roomGroup: this.roomGroup,
      roomIndex: index
    };
    this.emitService.roomGroup = data;
    this.navCtrl.navigateForward(['tabs/home/RoomPage'], {
      queryParams: data
    });
  }

  // 业务数据处理
  dealData(data): Observable<any> {
    return new Observable(responseObserver => {
      let arr;
      arr = {};
      arr.rooms = [];
      arr.rooms = data.datas;
      if (arr.rooms) {
        arr.rooms.map(function (each) {
          each.areaSerAlarmCount = 0;
          each.areaGenAlarmCount = 0;
        });
      }
      this.dataservice.getSystemsAlarmList(this.projectId, this.system.deviceSysId).subscribe(res => {
        if (res.data && res.data.length) {
          for (let i = 0; i < res.data.length; i++) {
            for (let j = 0; j < arr.rooms.length; j++) {
              if (res.data[i].areaId === arr.rooms[j].areaId) {
                if (res.data[i].alarmLevel === 2) {
                  arr.rooms[j].areaGenAlarmCount++;
                } else if (res.data[i].alarmLevel === 3) {
                  arr.rooms[j].areaSerAlarmCount++;
                }
              }
            }
          }
        }
        responseObserver.next(arr);
        responseObserver.complete();
      });
    })
  }

  goBack() {
    this.navCtrl.pop();
  }
}
